#include "ms618_algbackd1tod8circle.h"

using namespace MeasurE618;

AlgBackD1toD8Circle::AlgBackD1toD8Circle(int i):AlgBase(i)
{

}

void AlgBackD1toD8Circle::operator()(cv::Mat &srcImg,
                                     int id,
                                     std::map<string, float> &measRes,
                                     int fixtureId)
{
    //背光图小半圆边缘提取  // CDL back图    \paras616\back\ cdL.xml
//    int NewCircleEdge(cv::Mat srcimg, const vector<int> paras, vector<cv::Point>& contours);

//    qDebug() << " ";

    std::vector<cv::Point> resptVec;

    for(auto i=9;i<17;i++)
    {
        std::vector<int> tparas;
        for(auto j=0;j< m_dataAllVec[i].m_edgeParam.cols;j++)
        {
            tparas.push_back(m_dataAllVec[i].m_edgeParam.at<int>(i-9,j));
        }
        //paras.push_back(tparas);
        std::vector<cv::Rect> rangVec;
        TemplateMatch(srcImg,m_dataAllVec[i],rangVec);
        cv::Mat imgt=srcImg(rangVec[0]).clone();
        std::vector<cv::Point> contours;
        edgedetect obj;
        obj.NewCircleEdge(imgt,tparas,contours);
        ImageCoordinateTransformation(contours,rangVec);

        std::unique_lock<std::mutex> lock(*AlgBase::mtxptrVec[id]);
        while (!AlgBase::flagVec[id])
        {
            (*AlgBase::cvarptrVec[id]).wait(lock);
        }
        for(auto &elem:contours)
        {
            cv::Point2f ptsIn(static_cast<float>(elem.x),
                              static_cast<float>(elem.y)),
                              ptsOut;

            CoordinateTransformationRelateToDot(datumBackVec[id], ptsIn, ptsOut);
            resptVec.push_back(ptsOut);
        }
    }

    edgedetect obj;
    vector<float> cirres=obj.FitCircle(resptVec);

    std::string prefix = m_xmlFileNamePre + to_string(fixtureId) + "_";

    measRes.insert(std::make_pair(string("FAI74-D-X-distance_pixel"), cirres[0]));
    float fai74dx = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI74-D-X-distance")], cirres[0]);
    measRes.insert(std::make_pair(string("FAI74-D-X-distance_real"), fai74dx));

    measRes.insert(std::make_pair(string("FAI74-D-Y-distance_pixel"), -cirres[1]));
    float fai74dy = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI74-D-Y-distance")], -cirres[1]);
    measRes.insert(std::make_pair(string("FAI74-D-Y-distance_real"), fai74dy));

    CalcPosition(prefix + "FAI74-D-X-distance", prefix + "FAI74-D-Y-distance", "FAI74-D-position", prefix,
                 obj, m_standardValMap["FAI74-D-X-distance"], m_standardValMap["FAI74-D-Y-distance"],
                 cirres[0], -cirres[1], measRes);

    measRes.insert(std::make_pair(string("FAI73-D-diam_pixel"), cirres[2]*2));
    float fai73dd = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI73-D-diam")], cirres[2]*2);
    measRes.insert(std::make_pair(string("FAI73-D-diam_real"), fai73dd));

    qDebug() << "E618 alg back d1 to d8 circle end";
}
